﻿using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using MS.InformationManagement.Presenter.Support;
using MS.InformationManagement.Presenter.DocumentPrinter;
using System.Collections.Generic;
using MS.InformationManagement.DAL.DocumentCenter;
using System.Data;
using MS.InformationManagement.Core.TransactionsResponse;
using MS.InformationManagement.Support;

namespace MS.InformationManagement.WP.DocumentCenter.ShippingList
{
    public partial class ShippingListUserControl : BaseControl, IDeliveryDocumentsView
    {

        #region Fields

        DeliveryDocumentPresenter _presenter;
        double _totalCost = 0;

        #endregion

        #region Public Methods

        public IEnumerable<Zona> DeliveryZones { get; set; }

        public IEnumerable<MedioDeEnvio> DeliveryMeans { get; set; }

        public int TotalItems { get; set; }

        public int PageSize { get { return 20; } }

        public int PageIndex { get { return 0; } }

        public List<EnvíoDeCorrespondencia> PendingDeliveries { get; set; }

        public int SelectedDeliveryId { get { return int.Parse(ddlModosEnvio.SelectedValue); } }

        public string SelectedDeliveryZone { get { return ddlZone.SelectedItem.Text; } }

        public DeliveryFormCreationResponse DeliveryFormResponse { get; set; }

        #endregion

        #region Form Events

        protected void DeliveryFormGeneration(object sender, EventArgs e)
        { 
            try
            {
                _presenter.DeliveryFormGeneration();
            }
            catch(Exception ex)
            {
                HandleError(ex);
            }     
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                _presenter = new DeliveryDocumentPresenter(this);
                _presenter.HandleLoad();
                if (IsPostBack) return;
                _presenter.LoadInitialData();
            }
            catch(Exception ex)
            {
                HandleError(ex);
            }
        }

        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
        }

        protected void deliveryDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
                _totalCost += ((EnvíoDeCorrespondencia)(e.Row.DataItem)).CostoDelEnvío.Value;

            if (e.Row.RowType != DataControlRowType.Footer) return;

            Label totalColumn = e.Row.FindControl("totalCost") as Label;
            totalColumn.Text = string.Format("{0:C}", _totalCost);
        }

        #endregion

        #region Implemented Methods

        public void UpdateShippingList()
        {
            try
            {
                _presenter.HandleLoad();    
            }
            catch(Exception ex)
            {
                HandleError(ex);
            }            
        }

        public void Show()
        {

            //Configure grid
            grdPendingDocuments.AllowGrouping = true;
            grdPendingDocuments.GroupFieldDisplayName = "Modo Envio";
            grdPendingDocuments.GroupField = "DescripcionModoEnvio";
            grdPendingDocuments.AllowSorting = true;
            grdPendingDocuments.AllowGroupCollapse = true; 

            //Data Binding
            grdPendingDocuments.DataSource = PendingDeliveries;
            grdPendingDocuments.DataBind();

        }

        public void LoadInitialData()
        {
            //Setting delivery means
            ddlModosEnvio.DataSource = DeliveryMeans;
            ddlModosEnvio.DataBind();

            //Setting delivery zones
            ddlZone.DataSource = DeliveryZones;
            ddlZone.DataBind();
        }

        public void ShowDeliveryForm()
        {
            //Clear headers
            Response.ClearContent();
            Response.ClearHeaders();

            //Setting headers
            Response.AddHeader("Content-Disposition", "attachment;filename=" + DeliveryFormResponse.DocumentName);

            //Tipo MIME del archivo a descargar. Si tienen diferentes tipos de archivos hacen un case
            //Response.ContentType = "application/msword"

            Response.ContentType = "application/pdf";

            //Cabecera que establece el tamaÒo de la respuesta (tamaÒo del archivo en bytes) 
            Response.AddHeader("Content-length", DeliveryFormResponse.DeliveryContent.Length.ToString());

            //Se escribe la respuesta al usuario que ver· la ventana de descarga del archivo. 
            Response.BinaryWrite(DeliveryFormResponse.DeliveryContent);

            this.UpdateShippingList();
        }


        #endregion


    }
}
